// pages/jqq/player.js
let index

Page(
  {timeupdate(e){
  this.currentTime=e.detail.currentTime
},
onHide(){this.save()},
onUnload(){this.save()},
save(){
  if(!this.data.sources)return
  let playMessage={ ...this.data }
  delete playMessage.__webviewId__
  let pages=getCurrentPages() //获取当前页面栈。数组中第一个元素为首页，最后一个元素为当前页面。
  let prePage=pages[pages.length-2] //获取视频列表页面对象
  let data=prePage.data //视频列表页面的页面数据
  let menu=data.menus[data.menuIndex] //获取当前菜单项
  let type=menu.types[menu.typeIndex] //获取当前类型
  let video=type.list[index] //获取要播放的视频对象
  let change={} //保存有变化的数据
  change[`menus[${data.menuIndex}].types[${menu.typeIndex}].list[${index}].playMessage`]=playMessage
  prePage.setData(change)
},
	request(url){ 
		return new Promise((resolve, reject)=>{
			wx.request({
				url,
				success: r => {
					resolve(r.data) 
				},
				fail: e=>{
					resolve(null) 
				}
			})
		})
	},
	async onLoad(options) { 
		this.host='https://jqqzx.cc'
		// console.log(options) // options={index: "0"}
		index=parseInt(options.index) 
		let pages=getCurrentPages() 
		let prePage=pages[pages.length-2] 
		let data=prePage.data 
		let menu=data.menus[data.menuIndex] 
		let type=menu.types[menu.typeIndex] 
    let video=type.list[index] 
    if(video.playMessage){
			this.setData(video.playMessage)
			return
		}
		let url=`${this.host}${video.url}` 
		let html=await this.request(url) 
		if(html!=null){ 
      // console.log(html)
      console.log("网页内容："+html)
      let change={}
			let regex=/<div class="module-info-introduction-content">(.+?)<\/div>/s
			let r=regex.exec(html)
      if(r!=null)change.jj=r[1].replace(/(<\/?(p|br)[^>]*>|　)+/g,'\n　　')
			let sources=[] //存放数据源
			regex=/data-dropdown-value="([^"]+)"/g
			while(r=regex.exec(html)){
				sources.push({
					name: r[1],
				})
			}
			regex=/<div class="module-play-list-content  module-play-list-base">(.+?)<\/div>/gs
			let index=-1
			while(r=regex.exec(html)){
				let r2, list=[], regex2=/href="([^"]+)" title="[^"]+"><span>([^<]+)/g
				while(r2=regex2.exec(r[1])){
					list.push({
						url: r2[1],
						title: r2[2],
					})
				}
				sources[++index].list=list
      }
      change.sources=sources
      this.setData(change)
		}
	},
  sources(e){
		let index=e.target.dataset.index 
		if(index==null)return 
		let change={sourceIndex: index} 
		let oldIndex=this.data.sourceIndex 
		if(oldIndex!=null)change[`sources[${oldIndex}].selected`]=false
		change[`sources[${index}].selected`]=true
		this.setData(change)
  },
  play(e){
		let index=e.target.dataset.index //获取点击视频的索引号
		if(index==null)return //点击到空白地方了
		let sourceIndex=this.data.sourceIndex //单管源的索引号
		let source=this.data.sources[sourceIndex] //获取当前数据源
		let change={} //记录有变化的数据
		change[`sources[${sourceIndex}].listIndex`]=index 
		change[`sources[${sourceIndex}].list[${index}].selected`]=true 
		this.setData(change)
	}
})